﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
namespace PowerHub.MES.Common.Utility
{
    public static class GaoDeMapAPI
    {
        public const string Key = "6da7356e94c4b115d71e89b93695d481";

        /// <summary>
        /// 高德地图IP转地名
        /// https://lbs.amap.com/api/webservice/guide/api/ipconfig
        /// </summary>
        /// <param name="ip"></param>
        public async static Task<IPLocation> GetIPLocation(string ip)
        {
            IPLocation result = new IPLocation();
            using (var client = new HttpClient())
            {
                string url = $"https://restapi.amap.com/v3/ip?key={Key}&ip={ip}";
                var response = await client.GetAsync(url);

                if (response.IsSuccessStatusCode)
                {
                    string json = await response.Content.ReadAsStringAsync();

                    result = JsonConvert.DeserializeObject<IPLocation>(json);
                }
                else
                {
                    result.status = "0";
                }
            }

            return result;
        }
    }

    [Serializable]
    public class IPLocation
    {
        /// <summary>
        /// <para>返回结果状态值</para>
        /// <para>值为0或1,0表示失败；1表示成功</para>
        /// </summary>
        public string status;

        /// <summary>
        /// <para>返回状态说明</para>
        /// <para>返回状态说明，status为0时，info返回错误原因，否则返回“OK”。</para>
        /// </summary>
        public string info;

        /// <summary>
        /// <para>状态码</para>
        /// <para>https://lbs.amap.com/api/ios-sdk/guide/map-tool/errorcode</para>
        /// </summary>
        public string infoCode;

        /// <summary>
        /// <para>省份名称</para>
        /// <para>若为直辖市则显示直辖市名称</para>
        /// <para>如果在局域网 IP网段内，则返回“局域网”</para>
        /// <para>非法IP以及国外IP则返回空</para>
        /// </summary>
        public string province;

        /// <summary>
        /// <para>城市名称</para>
        /// <para>示例:石家庄市</para>
        /// </summary>
        public string city;

        /// <summary>
        /// <para>城市的adcode编码</para>
        /// <para>示例:130100</para>
        /// </summary>
        public string adcode;

        /// <summary>
        /// <para>所在城市矩形区域范围</para>
        /// <para>所在城市范围的左下右上对标对</para>
        /// <para>示例:114.2195964,37.86302147;114.7912717,38.22308596</para>
        /// </summary>
        public string rectangle;
    }
}
